<?php

namespace App\Listeners\SiteLocation;

use App\Events\SiteLocation\WhiteListEvent;
use App\Models\Common\ConfigModel;
use App\Models\SiteLocation\SiteLocationWhiteListModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Arr;

class WhiteListListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param WhiteListEvent $event
     * @return void
     */
    public function handle(WhiteListEvent $event)
    {
        // 获得白名单内的用户
        $userInfo = [];
        SiteLocationWhiteListModel::query()
            ->where('status', SiteLocationWhiteListModel::STATUS_ON)
            ->chunkById(100, function ($lists) use (&$userInfo) {
                foreach ($lists as $list) {
                    $provinceCodeArr = Arr::collapse(json_decode($list->appPower, true));

                    if (empty($provinceCodeArr)) {
                        continue;
                    }

                    $userInfo[] = [
                        "userId"          => $list->rmsUserId,
                        "provinceCodeArr" => Arr::collapse(json_decode($list->appPower, true)),
                    ];
                }
            });

        // 修改白名单
        ConfigModel::query()
            ->where('module', 'wanggui')
            ->where('name', 'regionalWhiteList')
            ->update([
                'value' => json_encode($userInfo, JSON_UNESCAPED_UNICODE)
            ]);
    }
}
